package om.jenkinslog;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.action.index.IndexRequest;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xiazhonghai
 * @date 2021/1/26 11:46
 * @description:
 */
public class TestLog extends Common implements Runnable {

    String baseurl;
    String path;
    String queryparam = "?limit_builds=400";
    ArrayList<String> joblinks = new ArrayList();
    HashMap<String, String> sbujoblinks = new HashMap();
    ObjectMapper objectMapper = new ObjectMapper();
    String esindex;


    public TestLog(String baseurl, String path, String community) {
        this.baseurl = baseurl;
        this.path = path;
        this.esindex = properties.getProperty(community + "_testesindex");
    }

    @Override
    public void run() {

        try {
            HttpGet httpGet = new HttpGet(baseurl + path+queryparam);
            CloseableHttpResponse execute = httpclient.execute(httpGet);
            Document document = Jsoup.parse(EntityUtils.toString(execute.getEntity()));
            Elements links = document.getElementsByTag("a");
            for (Element link : links) {
                String href = link.attr("href");
                if (href.startsWith("/tests/")) {
                    joblinks.add(baseurl + href);
                }
            }
            if (joblinks.size() > 0) {
                for (String joblink : joblinks) {
                    HttpGet jobget = new HttpGet(joblink);
                    CloseableHttpResponse response = httpclient.execute(jobget);
                    if (response.getStatusLine().getStatusCode() == 200) {
                        Document doc = Jsoup.parse(EntityUtils.toString(response.getEntity()));
                        Elements spans = doc.getElementsByTag("span");
                        for (Element span : spans) {
                            if (span.id().startsWith("res-")) {
                                String idstr = span.id();
                                String id = idstr.split("-")[1];
                                sbujoblinks.put(joblink+id, id);
                            }
                        }
                    }
                }
            }
            System.out.println(sbujoblinks);
            for (String value : sbujoblinks.values()) {
                HttpGet get = new HttpGet(baseurl + "/api/v1/jobs/" + value);
                CloseableHttpResponse response = httpclient.execute(get);
                if (response.getStatusLine().getStatusCode() == 200) {
                    String s = EntityUtils.toString(response.getEntity());
                    JsonNode jsonNode = objectMapper.readTree(s);
                    Map datamap = objectMapper.readValue(s, Map.class);
                    String group = ((Map) datamap.get("job")).get("group").toString();
                    String build = jsonNode.get("job").get("settings").get("BUILD").asText();
                    group=convert(group);
                    datamap.put("created_at",jsonNode.get("job").get("t_started").asText());
                    if("passed".equals(jsonNode.get("job").get("result").asText())){
                        datamap.put("success",1);
                    }
                    datamap.put("id",group+build);
                    System.out.println(datamap.get("id"));
                    bulkProcess.add(new IndexRequest(this.esindex).id((group+build)+jsonNode.get("job").get("test").asText()).source(datamap));
                }

            }
            bulkProcess.flush();
            bulkProcess.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            try {
                esClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //特殊转换处理
    public String convert(String name){
        HashMap<String, String> stringStringHashMap = new HashMap<>();
        stringStringHashMap.put("openEuler-build-daily","openEuler-Mainline");
        stringStringHashMap.put("openEuler-20.03-LTS-SP1-netinst","openEuler-20.03-LTS-SP1");
        for (Map.Entry<String, String> stringStringEntry : stringStringHashMap.entrySet()) {
            if(stringStringEntry.getKey().equals(name)){
                return stringStringEntry.getValue();
            }
        }
        return name;
    }
}
